//This servlet is used to explicitly rate and add any comments for a specific website.It is used by the rate_down.html and rate_up.html web pages. 
//Author:Shreyas Kamath

import java.sql.*;
import java.util.Date;
import java.io.*;
import java.util.*;
import java.util.HashMap;
import javax.servlet.http.*;
import javax.servlet.ServletException;
import javax.servlet.ServletConfig;

public class ExplicitRatingServlet extends HttpServlet{

	//Initialize the servlet	
	public void init(ServletConfig config)
	{
	  System.out.println("ExplicitRatingServlet: init()");
	}
	
	//Service method of the servlet
	public void doPost(HttpServletRequest request,HttpServletResponse response)    
		throws ServletException, IOException 
	{
		// set the response type
		response.setContentType("text/xml; charset=UTF-8"); 
		response.setHeader("Cache-Control","no-cache");
		//Get the parameters
		String strNym=null;
		strNym=request.getParameter("nym");
		//String strNym="Home";
		String strUrl=null;
		strUrl=request.getParameter("url_val");
		//String strUrl="www.google3.com";
		String strRating=null;
		strRating=request.getParameter("rating");
		String strComment=null;
		strComment=request.getParameter("comment");
		//String strRating="5";		
		int success=0;
		if(strNym !=null)
		success=this.AddExplicitRating(strNym,strUrl,strRating,strComment);
		// obtain the writer to write the response
		PrintWriter out = response.getWriter();
		//Print out the xml file success indicates if the comment and the rating were successfuly inserted.
		out.println("<?xml version=\"1.0\"?>");  
		out.println("<Success>");
		out.println("<valid>");
		out.println(success);
		out.println("</valid>");
		out.println("</Success>");
		out.close();
	}
		
		
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
	// Connect()
	// Connects to the database
	// return value of type Connection
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * */	
	public static Connection Connect()
	{
		Connection conn = null;
		
		try
		{
			//Connect to the database
			String userName = "nettrust";
			String password = "nettrust06162006";
			String url= "jdbc:mysql://localhost/NetTrust";
			Class.forName ("com.mysql.jdbc.Driver").newInstance ();
			conn = DriverManager.getConnection (url, userName, password);
			System.out.println ("Database connection established");
		}
		catch( Exception e )
		{
			System.out.println("Connection failed");
		};  
		return( conn );
	}
	/* * * * * * * * * * * * * * * * * * * * * * * * * * *h * * */
	// end of function Connect()
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * */	
	
		
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
	// AddExplicitRating()
	// Modifies the database to add the explicit rating and comment for the url if url exists else it inserts the url with explicit rating and the comment.
	// return the success flag 
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * */	
	
	public static int AddExplicitRating(String strNymName,String strUrl,String strRating,String strComments)
	{
		ResultSet rsUrls;
		int iExistsUrl=0;
		Connection conn=Connect();
		String strUrlName=null;
		String strNymID=GetNymID(strNymName);
		float fRating=Float.parseFloat(strRating);
		try
		{
			Statement stAddExplicitRating=conn.createStatement();
			Statement stUrlNames=conn.createStatement();
			//Check if url already exists for that particular nym in the database.
			rsUrls=stUrlNames.executeQuery("select urlName from internalrating where Nymid= '"+strNymID+"'"); 
			while(rsUrls.next())
			{
				strUrlName=rsUrls.getString("urlName");
				if(strUrlName.equals(strUrl))
				{
					iExistsUrl=1;
					break;
				}
			}
			//If url exists then we will update the explciit rating and the comment to reflect to the new values.
			if(iExistsUrl==1)
			{
				stAddExplicitRating.executeUpdate("update internalrating set ExplicitRating='"+fRating+"' ,Comments='"+strComments+"' where urlName='"+strUrl+"' and Nymid='"+strNymID+"'"); 
			}
			else
			{
				//Get the current time and then insert the url with the current time,explicit rating and comment into the database.
				Date tmpDate = new Date();
				long lTmpCurrTime = tmpDate.getTime();
				String strTmpCurrTime = Long.toString( lTmpCurrTime );
				stAddExplicitRating.executeUpdate("insert into internalrating values('"+strUrl+"','"+strTmpCurrTime+"','1','"+fRating+"',0,'"+strComments+"','"+strNymID+"','"+strTmpCurrTime+"')");
			}
			//return success flag
			return 1;
		}
		catch(Exception e)
		{
			System.out.println(" The following Exception occured"+e);
			//return error flag
			return 0;
		}
	}
	
		
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
	// GetNymID()
	// Gets the 128 bit NymID corresponding to a nym using the nym name as the parameter
	// returns 128 bit NymID
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * */	
	public static String GetNymID(String strNym)
	{
		Connection conn =Connect();
		String strNymid=null;
		ResultSet rsNymID;
		try
		{
			Statement getNymID= conn.createStatement();
		      //Get the nymid corresponding to the nym name from the database 
			rsNymID=getNymID.executeQuery("select nymid from nymnamemap where nymname='" + strNym + "'");
			while( rsNymID.next() )
			{
				strNymid=rsNymID.getString("nymid");
			}
		}
		catch( Exception e )
		{
			System.out.println ( "Database Exception is " + e );
		};  
		return(strNymid);
	}	
		
	
	
	public void destroy() {
		System.out.println("ExplicitRatingServlet: destroy()");
	}
}